package com.evolution.common.core.factory;

import com.evolution.common.core.utils.StringUtils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.lang.NonNull;

import java.io.IOException;
import java.util.Objects;

/**
 * Class: YamlPropertySourceFactory
 * <p>
 * desc: Y[a]!ml property source file reader
 * </p>
 * create date: 2024-03-11 11:09:12
 *
 * @author cao.yong
 */
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {

    @NonNull
    @Override
    public PropertySource<?> createPropertySource(String name, @NonNull EncodedResource resource) throws IOException {
        String filename = resource.getResource().getFilename();
        if (StringUtils.isNotBlank(filename) && StringUtils.endWithAny(filename, ".yml", ".yaml")) {
            YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
            factoryBean.setResources(resource.getResource());
            factoryBean.afterPropertiesSet();
            return new PropertiesPropertySource(filename, Objects.requireNonNull(factoryBean.getObject()));
        }
        return super.createPropertySource(name, resource);
    }
}
